import React from 'react'
import { connect } from 'react-redux'
import Style from './index.scss'
import Nav from '@components/nav'
import API from '@common/api'
import update from 'react-addons-update'
import Recommend from './components/recommend'
import DynamicList from './components/dynamic-list'
import PostTopic from './components/post_topic'

@connect(
  store => ({
    topicList: store.topicList
  }),
  dispatch => ({
    addTopicList: info => {
      dispatch({
        type: 'ADD_TOPICLIST',
        info: info
      })
    }
  })
)
class Detail extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      followList: [],
      showPostTopic: false
    }
    this.initRecommendFriendList()
    this.initFriendTopic()
  }

  initRecommendFriendList = async () => {
    let response = await API.recommendList()
    let followList = response.data.map(item => {
      item.hasFollow = false
      return item
    })
    this.setState(() => ({
      followList
    }))
  }

  initFriendTopic = async () => {
    let response = await API.friendTopicList()

    this.props.addTopicList(response.data)
  }

  setFollowState = async (index, status) => {
    let followList = this.state.followList
    await API.followUser({
      userId: followList[index].userId,
      status: status ? 1 : 0
    })

    //  awesome
    this.setState({
      followList: update(this.state.followList, {
        [index]: {
          hasFollow: { $set: status }
        }
      })
    })
  }

  togglePostTopic = async () => {
    this.setState(value => ({
      showPostTopic: !value.showPostTopic
    }))
  }

  render() {
    return (
      <main>
        <Nav />
        {!this.state.showPostTopic ? null : (
          <PostTopic togglePostTopic={this.togglePostTopic} />
        )}
        <div className="page-container">
          <span className="loading" />
          <div className={Style['home-detail']}>
            <DynamicList />
            <Recommend
              followList={this.state.followList}
              setFollowState={this.setFollowState}
              togglePostTopic={this.togglePostTopic}
            />
          </div>
        </div>
      </main>
    )
  }
}

export default Detail
